
#for consistanciy with easy_phot numpy is imported without identifier.
#this makes it hard to know where functions come from. In the future it is preferable to use import numpy as np and precede numpy functions with np.
from numpy import *
import easy_phot_params as param 
#SciPy Cookbook smoothing.
def smooth(x,window_len=11,window='hanning'):
    """smooth the data using a window with requested size.
    
    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal 
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.
    
    input:
        x: the input signal 
        window_len: the dimension of the smoothing window; should be an odd integer
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal
        
    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)
    
    see also: 
    
    numpy.hanning, hamming, bartlett, blackman, convolve
    scipy.signal.lfilter
 
    TODO: the window parameter could be the window itself if an array instead of a string
    NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
    """

    if x.ndim != 1:
        raise ValueError, "smooth only accepts 1 dimension arrays."

    if x.size < window_len:
        raise ValueError, "Input vector needs to be bigger than window size."


    if window_len<3:
        return x


    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"


    s=r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
    #print(len(s))
    if window == 'flat': #moving average
        w=ones(window_len,'d')
    else:
        w=eval(''+window+'(window_len)')

    y=convolve(w/w.sum(),s,mode='valid')
    y=y[(window_len/2-1):-(window_len/2)]
    return y


def plotphot(datafile="lc.txt"):
    #plot up the results
    import matplotlib.pyplot as plt
    import numpy as np
    fig=plt.figure(figsize=(10,7))

    #  import easy_phot
    if datafile=="lc.txt":
        print("assuming data file is lc.txt and in the working directory")
    ls = np.genfromtxt(datafile)
    mean=np.average(ls[:,3::2],axis=1)
    sumsq=np.sqrt(np.sum(ls[:,4::2]**2,axis=1))/ls.shape[1]
    time=ls[:,0]
    plt.subplot(311)
    plt.plot(time,mean,'-*',label="mean magnitude")
    plt.errorbar(time, ls[:,1],fmt='.',yerr=sumsq,label="star #0")
    plt.xlabel("Hours")
    plt.ylabel("Magnitudues")
    plt.legend( prop={"size":8})
    plt.subplot(312)
    #plot mean of all stars versus first star: 
    plt.errorbar(time,mean - ls[:,1],fmt='.',yerr=sumsq,label='differential from avg.')
    plt.plot(time,smooth(mean - ls[:,1],window_len=6,window='hanning'),'--',label='smoothed')
    plt.xlabel("Hours")
    plt.ylabel("<m> - star #0")
    plt.legend( prop={"size":8})
    plt.subplot(313)
    stars=ls[:,1::2].transpose()
    stars[np.isnan(stars)]=0
    mean[np.isnan(mean)]=0
    for number,star in enumerate(stars):
        diff = star-mean
        plt.plot(time,diff/np.max(diff),'-x',label='star #'+str(number))
        plt.ylabel("$(m_*-<m>)/max(m_*-<m>)$")
    plt.legend( prop={"size":8})
    plt.xlabel("Hours")
    plt.savefig(param.image_dir+"photometry_plot.png")
